/*
@Time : 2020/12/30 5:45 下午
@Author : chenle
@File : validate
@Software: GoLand
*/
package lego

import (
	zhongwen "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
)

var validate *validator.Validate
var trans ut.Translator

func init() {
	zh := zhongwen.New()
	uni := ut.New(zh, zh)
	trans, _ = uni.GetTranslator("zh")

	validate = validator.New()
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		label := field.Tag.Get("comment")
		if label == "" {
			gorm := field.Tag.Get("gorm")
			gormList := strings.Split(gorm, ";")
			for _, v := range gormList {
				if strings.Contains(v, "comment") {
					comment := strings.Replace(strings.Split(v, ":")[1], "'", "", -1)
					comments := strings.Split(comment, " ")
					if len(comments) > 0 {
						label = comments[0]
					}
				}
			}
			if label == "" {
				return field.Name
			}
		}
		return label
	})
	zh_translations.RegisterDefaultTranslations(validate, trans)
}

func transError(err error) string {
	s, ok := err.(validator.ValidationErrors)
	if ok {
		for _, value := range s.Translate(trans) {
			return value
		}
	} else {
		return err.Error()
	}
	return "参数错误"
}
